 import { setToken,removeToken } from '@/util/auth'
import { setStore, getStore } from '@/util/store'
import { isURL, validatenull } from '@/util/validate'
import website from '@/config/website'
import { getTenantCode, refreshToken, loginByUsername, getMenu, logout } from '@/api/user'


function addPath (ele) {
  const menu = website.menu;
  const propsConfig = menu.props;
  const propsDefault = {
    label: propsConfig.label || 'label',
    path: propsConfig.path || 'path',
    icon: propsConfig.icon || 'icon',
    children: propsConfig.children || 'children',
    hasChildren: 'hasChildren'
  }
  const icon = ele[propsDefault.icon];
  ele[propsDefault.icon] = validatenull(icon) ? menu.iconDefault : icon;
  ele.meta = {
    keepAlive: true,
    id: ele.id
  }

  ele.component = 'views' + ele[propsDefault.path];

  if (!ele[propsDefault.hasChildren] && isURL(ele[propsDefault.path]) && ele[propsDefault.path] != 'null') {
    ele[propsDefault.path] = ele[propsDefault.path]

  } else if (ele[propsDefault.hasChildren]) {
    (ele[propsDefault.children] || []).forEach(child => {
      if (!isURL(child[propsDefault.path])) {
        child[propsDefault.path] = child[propsDefault.path]
      }
      child.component = 'views' + child[propsDefault.path]
      addPath(child);
    })
  }

}
const user = {
  state: {
    userInfo: getStore({ name: 'userInfo' }) || [],
    rolesId: getStore({ name: 'rolesId' }) || [],
    permission: {},
    cid: getStore({ name: 'cid' }),
    passFlag: getStore({ name: 'passFlag' }),
    menuId: getStore({ name: 'menuId' }) || [],
    menu: getStore({ name: 'menu' }) || [],
    menuAll: getStore({ name: 'menuAll' }) || [],
    expiresIn: getStore({ name: 'expiresIn' }) || undefined,
    token: getStore({ name: 'token' }) || '',
    tokenType: getStore({ name: 'tokenType' }) || '',
    rtoken: getStore({ name: 'rtoken' }) || '',
    tenantCode: getStore({ name: 'tenantCode' }) || '',
    logo: getStore({ name: 'logo' }) || '',
  },
  actions: {
    //根据用户名登录
    LoginByUsername ({ commit }, user) {
      return new Promise((resolve, reject) => {
        const params = {
          loginId: user.username,
          passWord: window.md5(user.password).toUpperCase()
        }
        if (user.tenantCode) {
          commit('SET_TENANTCODE', user.tenantCode);
          params.tenantCode = user.tenantCode
        }
        params.grantType = 'password';
        const header = {};
        if (website.isCaptcha){
          params.grantType = 'captcha';
          header['Captcha-Code'] = user.code;
          header['Captcha-Key'] = user.key;
        }
        loginByUsername(params,header).then(res => {
          const data = res.data.data;
          commit('SET_USERIFNO', Object.assign(data.user, {
            username: user.username,
            name: data.user.nickName,
            avatar: window.urllist.download+data.user.avatar,
            avatarBase: data.user.avatar
          }, data.user.orgId));
          commit('SET_EXPIRESIN', data.expiresIn);
          commit('SET_TOKEN_TYPE', data.tokenType);
          commit('SET_RTOKEN', data.refreshToken);
          commit('SET_TOKEN', data.accessToken);
          commit('SET_ROLES_ID', data.user.roleIds);
          commit('DEL_ALL_TAG');
          commit('CLEAR_LOCK');
          commit('CLEAR_MENUBTNPER');
          resolve();
        }).catch(err => {
          reject(err);
        })
      })
    },
    // 获取租户ID
    GetTenantCode ({ commit }) {
      return new Promise((resolve) => {
        getTenantCode().then(res => {
          const data = res.data.data;
          commit('SET_TENANTCODE', data.tenantCode || '');
          resolve(data);
        })
      })
    },

    //根据手机号验证码登录
    LoginByPhoneCode ({ commit }, user) {
      return new Promise((resolve, reject) => {

        const params = {
          phone: user.phone,
          phoneCode: user.code
        }
        if (user.tenantCode) {
          commit('SET_TENANTCODE', user.tenantCode);
          params.tenantCode = user.tenantCode
        }
        params.grantType = 'phone';

        loginByUsername(params, {}).then(res => {
          const data = res.data.data;
          commit('SET_USERIFNO', Object.assign(data.user, {
            username: data.userName,
            name: data.user.nickName,
            avatar: window.urllist.download+data.user.avatar,
            avatarBase: data.user.avatar
          }, data.user.orgId));
          commit('SET_EXPIRESIN', data.expiresIn);
          commit('SET_TOKEN_TYPE', data.tokenType);
          commit('SET_RTOKEN', data.refreshToken);
          commit('SET_TOKEN', data.accessToken);
          commit('SET_ROLES_ID', data.user.roleIds);
          commit('DEL_ALL_TAG');
          commit('CLEAR_LOCK');
          commit('CLEAR_MENUBTNPER');
          resolve();
        }).catch(err => {
          reject(err);
        })
      })
    },
    // GetUserInfo ({ commit }) {
    //   return new Promise((resolve, reject) => {
    //     getUserInfo().then((res) => {
    //       const data = res.data.data;
    //       // commit('SET_ROLES_ID', data)
    //       resolve(data);
    //     }).catch(err => {
    //       reject(err);
    //     })
    //   })
    // },
    //刷新token
    RefeshToken ({ state, commit }) {
      return new Promise((resolve, reject) => {
        refreshToken(state.rtoken).then(res => {
          if (res.status != 200) {
            reject(res.data.message)
            return
          }
          const data = res.data.data;
          // website.tokenTime = data.expiresIn;
          commit('SET_EXPIRESIN', data.expiresIn);
          commit('SET_RTOKEN', data.refreshToken);
          commit('SET_TOKEN_TYPE', data.tokenType);
          commit('SET_TOKEN', data.accessToken);
          commit('SET_TENANTCODE', data.user.tenantCode || '');
          resolve(data);
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登出
    LogOut ({ commit }) {
      return new Promise((resolve, reject) => {
        // console.log(store.getters.userInfo)
        logout({
          "userId": this.state.user.userInfo.userId
        }).then(() => {
          commit('SET_TENANTCODE', '')
          commit('SET_EXPIRESIN', undefined);
          commit('SET_TOKEN', '')
          commit('SET_TOKEN_TYPE', '')
          commit('SET_MENUID', {})
          commit('SET_MENUALL', []);
          commit('SET_MENU', [])
          commit('SET_TAG_LIST', [])
          commit('DEL_ALL_TAG');
          commit('CLEAR_LOCK');
          commit('CLEAR_MENUBTNPER');
          commit('SET_ROLES_ID', '');
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    //注销session
    FedLogOut ({ commit }) {
      return new Promise(resolve => {
        commit('SET_TENANTCODE', '')
        commit('SET_ROLES_ID', '');
        commit('SET_EXPIRESIN', undefined);
        commit('SET_TOKEN', '')
        commit('SET_TOKEN_TYPE', '')
        commit('SET_MENUID', {})
        commit('SET_MENUALL', []);
        commit('SET_MENU', [])
        commit('SET_TAG_LIST', [])
        commit('DEL_ALL_TAG');
        commit('CLEAR_LOCK');
        commit('CLEAR_MENUBTNPER');
        removeToken()
        resolve()
      })
    },
    // GetTopMenu () {
    //   return new Promise(resolve => {
    //     getTopMenu().then((res) => {
    //       const data = res.data.data || []
    //       resolve(data)
    //     })
    //   })
    // },
    // 获取系统菜单
    GetMenu ({ commit }) {
      return new Promise(resolve => {
        getMenu().then((res) => {
          let menu = res.data.data
          menu.forEach(ele => {
            addPath(ele, true);
          })
          commit('SET_MENU', menu)
          resolve(menu)
        })
      })
    },
  },
  mutations: {
    SET_TENANTCODE: (state, tenantCode) => {
      state.tenantCode = tenantCode;
      setStore({ name: 'tenantCode', content: state.tenantCode })
    },
    SET_TOKEN: (state, token) => {
      setToken(token);
      state.token = token;
      setStore({ name: 'token', content: state.token });
    },
    SET_EXPIRESIN: (state, expiresIn) => {
      state.expiresIn = expiresIn;
      setStore({ name: 'expiresIn', content: state.expiresIn });
    },
    SET_TOKEN_TYPE: (state, tokenType) => {
      state.tokenType = tokenType;
      setStore({ name: 'tokenType', content: state.tokenType })
    },
    SET_RTOKEN: (state, token) => {
      state.rtoken = token;
      setStore({ name: 'rtoken', content: state.rtoken })
    },
    SET_ROLES_ID (state, rolesId) {
      state.rolesId = rolesId;
      setStore({ name: 'rolesId', content: state.rolesId })
    },
    SET_MENUID (state, menuId) {
      state.menuId = menuId;
      setStore({ name: 'menuId', content: state.menuId, type: 'session' })
    },
    SET_PASSFLAG (state, passFlag) {
      state.passFlag = passFlag;
      setStore({ name: 'passFlag', content: state.passFlag, type: 'session' })
    },
    SET_LOGO (state, logo) {
      state.logo = logo;
      setStore({ name: 'logo', content: state.logo })
    },
    SET_USERIFNO: (state, userInfo) => {
      state.userInfo = userInfo;
      setStore({ name: 'userInfo', content: state.userInfo })
    },
    SET_MENUALL: (state, menuAll) => {
      state.menuAll = menuAll
      setStore({ name: 'menuAll', content: state.menuAll })
    },
    SET_MENU: (state, menu) => {
      state.menu = menu
      setStore({ name: 'menu', content: state.menu })
      if (validatenull(menu)) return
      //合并动态路由去重
      let menuAll = state.menuAll;
      menuAll = menuAll.concat(menu).reverse();
      let newMenu = [];
      for (let item1 of menuAll) {
        let flag = true;
        for (let item2 of newMenu) {
          if (item1.label == item2.label || item1.path == item2.path) {
            flag = false;
          }
        }
        if (flag) newMenu.push(item1);
      }
      state.menuAll = newMenu
      setStore({ name: 'menuAll', content: state.menuAll, })
    }
  }

}
export default user